﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.IO;
using System.Reflection;

namespace IdentityServer
{
    /// <summary>
    /// 根据实体类生成数据库表
    /// </summary>
    public class CreateTableServics
    {
        public static void Run()
        {
            ArrayList arrayListNo = new ArrayList();
            arrayListNo.Add("Entity");
            arrayListNo.Add("TreeEntity");
            arrayListNo.Add("TreeEntity`1");

            try
            {
                var dba = DbFactory.DbHelper("Data Source=127.0.0.1;Database=master;User ID=sa;Password=123456;MultipleActiveResultSets=true;Connect Timeout=30;Min Pool Size=16;Max Pool Size=100;");
                dba.ExecuteNonQuery("if exists (select * from sys.databases where name = 'IdentityServer')drop database [IdentityServer];CREATE DATABASE [IdentityServer];");

                var types = AppDomain.CurrentDomain.GetAssemblies()
                    .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IEntity))))
                    .ToArray();

                IDbHandleBase dp = DbFactory.DbHelper();
                foreach (Type type in types)
                {
                    if (!arrayListNo.Contains(type.Name))
                    {
                        dp.CreateTable(type);
                        Console.WriteLine("生成" + type.Name + "数据库表...");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("生成数据库表错误："+ex.Message);
            }
            Console.ForegroundColor = ConsoleColor.DarkGreen;
        }
    }
}
